﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace StableDiffusionTools.Utils
{
    public class IOUtil
    {
        private static readonly char[] defaultTrimChars = { ' ' };
        public static string RemoveIllegalPathCharacters(string source, char[] trimChars = null, string replacement = "")
        {
            trimChars = trimChars ?? defaultTrimChars;
            string rgPattern = @"[\\\/:\*\?""<>|]";
            Regex objRegEx = new Regex(rgPattern);
            string result = objRegEx.Replace(source, replacement);
            if (trimChars.Length > 0) result = result.Trim(trimChars);
            return result;
        }

        public static string CreateBackupFilePath(string filePath)
        {
            string directoryName = Path.GetDirectoryName(filePath);
            string extension = Path.GetFileNameWithoutExtension(filePath);
            int i = 0;
            string newName = Path.Combine(directoryName, $"{extension}.bak");
            while (File.Exists(newName))
            {
                newName = Path.Combine(directoryName, $"{extension}({i++}).bak");
                if (i > 1000)
                    throw new InvalidOperationException();
            }
            return newName;
        }
    }
}
